package com.moyv.schoolbbs.service;

import android.os.Handler;

import com.moyv.schoolbbs.bean.UserInfo;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.moyv.schoolbbs.config.URLConstant.USERINFO_URL;
import static com.moyv.schoolbbs.util.HttpUtil.createClient;
import static com.moyv.schoolbbs.util.JsonUtil.parseJson;

/**
 * @author moyv
 */
public class UserInfoService {
    public void getUserInfo(int account, Handler handler) {
        String url = USERINFO_URL;
        OkHttpClient okHttpClient = createClient();
//        请求体
        FormBody formBody = new FormBody.Builder()
                .add("account", String.valueOf(account))
                .build();
//        发送请求操作
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("mainService.getUserInfo:请求失败");
//                发送404到主页
                handler.sendMessage(handler.obtainMessage(404));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("mainService.getPost:拿到main的响应对象");
                String responseData = response.body().string();
                System.out.println(responseData);
                UserInfo userInfo = parseJson(responseData, UserInfo.class);
                handler.sendMessage(handler.obtainMessage(200, userInfo));
            }
        });
    }
}
